package filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter(filterName = "CharsetFilter")
public class CharsetFilter implements Filter {

    private String encoding;

    public void destroy() {
    }

    public void doFilter(ServletRequest req1, ServletResponse resp1, FilterChain chain) throws ServletException, IOException {
//        强转
        HttpServletRequest req = (HttpServletRequest) req1;
        HttpServletResponse resp = (HttpServletResponse) resp1;
        //字符集
        resp.setContentType("text/html;charset=utf-8");
        resp.setCharacterEncoding(encoding);
        req.setCharacterEncoding(encoding);
        //发送
        chain.doFilter(req, resp);
    }

    public void init(FilterConfig config) throws ServletException {
//      接受默认信息
        encoding = config.getInitParameter("encoding");

    }

}
